﻿package _A_TJTable;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
import java.util.Arrays;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

/**
 * 2011-6-2 15:39:48
 * 
 * @author Administrator
 */
public class JTable_DefaultTableModel {
    JFrame frame;
    Container contentPane;
    JScrollPane jsp;
    JTable table;
    JButton addRowButton, deleteRowButton, addColumnButton, deleteColumnButton;
    JButton fitHeaderButton;

    public JTable_DefaultTableModel() {
        frame = new JFrame("表格组件测试");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        contentPane = frame.getContentPane();
        contentPane.setLayout(new BorderLayout());
        String name[] = { "姓名", "语文", "数学" };
        Object data[][] = { { "王鹏", 91, 100 }, { "李兵", 99, 89 }, { "肖龙", 100, 100 } };
        // 建立Model的方法1:
        DefaultTableModel dtm = new DefaultTableModel();
        for (int i = 0; i < name.length; i++) {
            dtm.addColumn(name[i]);
        }
        for (int i = 0; i < data.length; i++) {
            dtm.addRow(data[i]);
        }
        dtm.setColumnCount(10);
        dtm.setRowCount(10);
        // 建立Model的方法2:
        // DefaultTableModel dtm=new DefaultTableModel(data,name);
        table = new JTable(dtm);
        // 设置表格属性
        table.setRowHeight(30);
        table.setCellSelectionEnabled(true);
        table.setPreferredScrollableViewportSize(new Dimension(400, 100));
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        // 添加选择及修改监听事件
        table.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                int rows[] = table.getSelectedRows();
                int columns[] = table.getSelectedColumns();
                System.out.println("rows:" + Arrays.toString(rows));
                System.out.println("columns:" + Arrays.toString(columns));
            }
        });
        dtm.addTableModelListener(new TableModelListener() {
            public void tableChanged(TableModelEvent e) {
                System.out.println("第一行:" + e.getFirstRow() + ",最后一行:" + e.getLastRow() + ",列:" + e.getColumn());
                // System.out.println("")
            }
        });
        // 设置列属性
        TableColumnModel tcm = table.getColumnModel();
        tcm.setColumnMargin(10);
        for (int i = 0; i < dtm.getColumnCount(); i++) {
            TableColumn tc = tcm.getColumn(i);
            tc.setPreferredWidth(100);
            // tc.setMinWidth(50);
        }
        jsp = new JScrollPane(table);
        contentPane.add(jsp, BorderLayout.CENTER);
        // 添加一些修改表格的按钮
        addRowButton = new JButton("添加行");
        addRowButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                DefaultTableModel dtm = (DefaultTableModel) table.getModel();
                dtm.addRow(new Vector<Object>());
            }
        });
        deleteRowButton = new JButton("删除行");
        deleteRowButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                DefaultTableModel dtm = (DefaultTableModel) table.getModel();
                dtm.removeRow(dtm.getRowCount() - 1);
            }
        });
        addColumnButton = new JButton("添加列");
        addColumnButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                DefaultTableModel dtm = (DefaultTableModel) table.getModel();
                // dtm.addColumn("新列");
                dtm.setColumnCount(dtm.getColumnCount() + 1);
            }
        });
        deleteColumnButton = new JButton("删除列");
        deleteColumnButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // DefaultTableColumnModel
                // dtcm=(DefaultTableColumnModel)table.getColumnModel();
                // TableColumn tc=dtcm.getColumn(dtcm.getColumnCount()-1);
                // dtcm.removeColumn(tc);
                DefaultTableModel dtm = (DefaultTableModel) table.getModel();
                dtm.setColumnCount(dtm.getColumnCount() - 1);
                System.out.println(table.getColumnCount());
            }
        });
        fitHeaderButton = new JButton("自动调整表头宽度");
        fitHeaderButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 获得每一列所有行单元字符串的宽度和表头的宽度
                FontRenderContext frc = new FontRenderContext(new AffineTransform(), true, true);
                Font font = table.getFont();
                DefaultTableModel dtm = (DefaultTableModel) table.getModel();
                for (int i = 0; i < dtm.getColumnCount(); i++) {
                    int maxWidth;
                    String str = dtm.getColumnName(i).toString();
                    maxWidth = (int) font.getStringBounds(str, frc).getWidth();
                    for (int j = 0; j < dtm.getRowCount(); j++) {
                        Object object = dtm.getValueAt(j, i);
                        if (object == null) {
                            continue;
                        }
                        str = object.toString();
                        int width = (int) font.getStringBounds(str, frc).getWidth();
                        if (width > maxWidth) {
                            maxWidth = width;
                        }
                    }
                    TableColumn tc = table.getColumnModel().getColumn(i);
                    tc.setPreferredWidth(maxWidth + table.getColumnModel().getColumnMargin() * 2);
                }
            }
        });
        Box box = Box.createHorizontalBox();
        box.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        box.add(Box.createHorizontalGlue());
        box.add(addRowButton);
        box.add(Box.createHorizontalStrut(10));
        box.add(deleteRowButton);
        box.add(Box.createHorizontalStrut(10));
        box.add(addColumnButton);
        box.add(Box.createHorizontalStrut(10));
        box.add(deleteColumnButton);
        box.add(Box.createHorizontalStrut(10));
        box.add(fitHeaderButton);
        box.add(Box.createHorizontalGlue());
        box.setMaximumSize(box.getPreferredSize());
        contentPane.add(box, BorderLayout.SOUTH);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String args[]) {
        new JTable_DefaultTableModel();
    }
}
